﻿using Assets.Scripts.DL.Enemy.CommonEnemy;
using UnityEngine;

namespace Assets.Scripts.DL.Enemy.FlyEnemy {
	public class FlyMove : CommonState<Controller> {
		Timer _moveTimer;
		float _moveTime;
		public FlyMove(Controller controller, StateEnum stateName) : base(controller, stateName) {
			_moveTimer = _controller.StateData.AtkCdRecoder[StateName];
			AddConditionToSelf(() => true);

			//转向自己
			AddNewTransition(this.StateName, () => _moveTimer.Elapsed > _moveTime);
		}

		public override void Enter() {
			_controller.PlayAnim(StateName);
			var range = _controller.Config.MoveTimeRange;
			_moveTime = Random.Range(range.x, range.y);
			var playerPos = _controller.GetPlayerPos();
			var dir = playerPos != Vector3.zero ? GetPlayerDir(playerPos).normalized : Random.insideUnitCircle.normalized;
			_controller.Velocity = dir * _controller.Config.MoveSpeed;
			//Debug.Log(_controller.transform.position);

			var faceDir = dir.x > 0 ? 1 : -1;
			ChangeFaceDir(faceDir);
			//Debug.Log($"{playerPos},{_controller.transform.position}, {dir}");
			_moveTimer.Reset();
		}

		public override void Exit() {
			_moveTimer.Reset();
		}

		public override void Update() {
		}

		Vector2 GetPlayerDir(Vector2 PlayerPos)
			=> PlayerPos - (Vector2)_controller.transform.position;

		void ChangeFaceDir(int faceDir)
			=> _controller.transform.localScale = new Vector3(faceDir, 1, 1);
	}
}
